// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_qa_api_serv

import (
	"context"
	"time"

	"gitcode.com/lvupclub/lvup-api/dao"
	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_qa_api"
	"github.com/google/uuid"
)

// 只有学生可以提问
func (apiImpl *RoadmapQaApiImpl) AddThread(ctx context.Context, req *roadmap_qa_api.AddThreadRequest) (*roadmap_qa_api.AddThreadResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.AddThreadResponse{
			Code:   roadmap_qa_api.AddThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	exist, err := roadmap_dao.RoadmapInfoDao.Exist(ctx, req.RoadmapId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_qa_api.AddThreadResponse{
			Code:   roadmap_qa_api.AddThreadResponse_CODE_NO_ROADMAP,
			ErrMsg: "成长路线图不存在",
		}, nil
	}
	exist, err = roadmap_dao.RoadmapMemberDao.Exist(ctx, req.RoadmapId, sessItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &roadmap_qa_api.AddThreadResponse{
			Code:   roadmap_qa_api.AddThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixMilli()
	threadId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = roadmap_dao.ThreadInfoDao.Insert(sessCtx, &roadmap_dao.ThreadInfoDbItem{
			ThreadId:  threadId,
			RoadmapId: req.RoadmapId,
			BasicInfo: roadmap_dao.BasicThreadInfoDbItem{
				Name: req.BasicInfo.Name,
			},
			ThreadState:       roadmap_qa_api.THREAD_STATE_THREAD_STATE_OPEN,
			HasAnswerViewTime: false,
			AnswerViewTime:    0,
			AskUserId:         sessItem.UserId,
			AskViewTime:       nowTime,
			CreateTime:        nowTime,
			UpdateTime:        nowTime,
		})
		if err != nil {
			return nil, err
		}
		return &roadmap_qa_api.AddThreadResponse{
			Code:     roadmap_qa_api.AddThreadResponse_CODE_OK,
			ThreadId: threadId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.AddThreadResponse), nil
}

// 只有学生可以更新
func (apiImpl *RoadmapQaApiImpl) UpdateThreadBasic(ctx context.Context, req *roadmap_qa_api.UpdateThreadBasicRequest) (*roadmap_qa_api.UpdateThreadBasicResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.UpdateThreadBasicResponse{
			Code:   roadmap_qa_api.UpdateThreadBasicResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.UpdateThreadBasicResponse{
			Code:   roadmap_qa_api.UpdateThreadBasicResponse_CODE_NO_THREAD,
			ErrMsg: "问答会话不存在",
		}, nil
	}
	if threadItem.AskUserId != sessItem.UserId {
		return &roadmap_qa_api.UpdateThreadBasicResponse{
			Code:   roadmap_qa_api.UpdateThreadBasicResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = roadmap_dao.ThreadInfoDao.UpdateBasic(sessCtx, req.RoadmapId, req.ThreadId, &roadmap_dao.BasicThreadInfoDbItem{
			Name: req.BasicInfo.Name,
		})
		if err != nil {
			return nil, err
		}
		return &roadmap_qa_api.UpdateThreadBasicResponse{
			Code: roadmap_qa_api.UpdateThreadBasicResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.UpdateThreadBasicResponse), nil
}

func (apiImpl *RoadmapQaApiImpl) ViewThread(ctx context.Context, req *roadmap_qa_api.ViewThreadRequest) (*roadmap_qa_api.ViewThreadResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.ViewThreadResponse{
			Code:   roadmap_qa_api.ViewThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_qa_api.ViewThreadResponse{
			Code:   roadmap_qa_api.ViewThreadResponse_CODE_NO_ROADMAP,
			ErrMsg: "成长路线图不存在",
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.ViewThreadResponse{
			Code:   roadmap_qa_api.ViewThreadResponse_CODE_NO_THREAD,
			ErrMsg: "问答会话不存在",
		}, nil
	}
	if !(roadmapItem.OwnerUserId == sessItem.UserId || threadItem.AskUserId == sessItem.UserId) {
		return &roadmap_qa_api.ViewThreadResponse{
			Code:   roadmap_qa_api.ViewThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixMilli()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		if roadmapItem.OwnerUserId == sessItem.UserId {
			err = roadmap_dao.ThreadInfoDao.UpdateAnswerViewTime(sessCtx, req.RoadmapId, req.ThreadId, nowTime)
			if err != nil {
				return nil, err
			}
		} else {
			err = roadmap_dao.ThreadInfoDao.UpdateAskViewTime(sessCtx, req.RoadmapId, req.ThreadId, nowTime)
			if err != nil {
				return nil, err
			}
		}
		return &roadmap_qa_api.ViewThreadResponse{
			Code: roadmap_qa_api.ViewThreadResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.ViewThreadResponse), nil
}

// 只有学生可以更新
func (apiImpl *RoadmapQaApiImpl) UpdateThreadState(ctx context.Context, req *roadmap_qa_api.UpdateThreadStateRequest) (*roadmap_qa_api.UpdateThreadStateResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.UpdateThreadStateResponse{
			Code:   roadmap_qa_api.UpdateThreadStateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.UpdateThreadStateResponse{
			Code:   roadmap_qa_api.UpdateThreadStateResponse_CODE_NO_THREAD,
			ErrMsg: "问答会话不存在",
		}, nil
	}
	if threadItem.AskUserId != sessItem.UserId {
		return &roadmap_qa_api.UpdateThreadStateResponse{
			Code:   roadmap_qa_api.UpdateThreadStateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = roadmap_dao.ThreadInfoDao.UpdateState(sessCtx, req.RoadmapId, req.ThreadId, req.ThreadState)
		if err != nil {
			return nil, err
		}
		return &roadmap_qa_api.UpdateThreadStateResponse{
			Code: roadmap_qa_api.UpdateThreadStateResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.UpdateThreadStateResponse), nil
}

func (apiImpl *RoadmapQaApiImpl) ListThread(ctx context.Context, req *roadmap_qa_api.ListThreadRequest) (*roadmap_qa_api.ListThreadResponse, error) {
	emptyList := []*roadmap_qa_api.ThreadInfo{}

	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.ListThreadResponse{
			Code:       roadmap_qa_api.ListThreadResponse_CODE_WRONG_SESSION,
			ErrMsg:     "会话不存在",
			ThreadList: emptyList,
		}, nil
	}

	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_qa_api.ListThreadResponse{
			Code:       roadmap_qa_api.ListThreadResponse_CODE_NO_ROADMAP,
			ErrMsg:     "成长路线图不存在",
			ThreadList: emptyList,
		}, nil
	}

	if roadmapItem.OwnerUserId != sessItem.UserId {
		exist, err := roadmap_dao.RoadmapMemberDao.Exist(ctx, req.RoadmapId, sessItem.UserId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &roadmap_qa_api.ListThreadResponse{
				Code:       roadmap_qa_api.ListThreadResponse_CODE_NO_PERMISSION,
				ErrMsg:     "没有权限",
				ThreadList: emptyList,
			}, nil
		}
	}

	listParam := &roadmap_dao.ListThreadParams{
		RoadmapId:        req.RoadmapId,
		FiterByAskUserId: roadmapItem.OwnerUserId != sessItem.UserId,
		AskUserId:        sessItem.UserId,
		FilterByNew:      req.FilterByNew,
	}
	count, err := roadmap_dao.ThreadInfoDao.Count(ctx, listParam)
	if err != nil {
		return nil, err
	}
	threadItemList, err := roadmap_dao.ThreadInfoDao.List(ctx, listParam, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//补全用户信息
	userIdList := []string{}
	for _, threadItem := range threadItemList {
		userIdList = append(userIdList, threadItem.AskUserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	threadList := []*roadmap_qa_api.ThreadInfo{}
	for _, threadItem := range threadItemList {
		thread := threadItem.ToThreadInfo()
		userItem, ok := userItemMap[threadItem.AskUserId]
		if ok {
			thread.AskUserDisplayName = userItem.BasicInfo.DisplayName
			thread.AskUserLogoUri = userItem.BasicInfo.LogoUri
		}
		threadList = append(threadList, thread)
	}

	return &roadmap_qa_api.ListThreadResponse{
		Code:       roadmap_qa_api.ListThreadResponse_CODE_OK,
		TotalCount: count,
		ThreadList: threadList,
	}, nil
}

func (apiImpl *RoadmapQaApiImpl) GetThread(ctx context.Context, req *roadmap_qa_api.GetThreadRequest) (*roadmap_qa_api.GetThreadResponse, error) {
	emptyInfo := &roadmap_qa_api.ThreadInfo{
		BasicInfo: &roadmap_qa_api.BasicThreadInfo{},
	}

	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.GetThreadResponse{
			Code:   roadmap_qa_api.GetThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Thread: emptyInfo,
		}, nil
	}

	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_qa_api.GetThreadResponse{
			Code:   roadmap_qa_api.GetThreadResponse_CODE_NO_ROADMAP,
			ErrMsg: "成长路线图不存在",
			Thread: emptyInfo,
		}, nil
	}

	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.GetThreadResponse{
			Code:   roadmap_qa_api.GetThreadResponse_CODE_NO_THREAD,
			ErrMsg: "问答会话不存在",
			Thread: emptyInfo,
		}, nil
	}
	if !(roadmapItem.OwnerUserId == sessItem.UserId || threadItem.AskUserId == sessItem.UserId) {
		return &roadmap_qa_api.GetThreadResponse{
			Code:   roadmap_qa_api.GetThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "问答会话不存在",
			Thread: emptyInfo,
		}, nil
	}
	//获取用户信息
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, []string{threadItem.AskUserId})
	if err != nil {
		return nil, err
	}
	thread := threadItem.ToThreadInfo()
	if len(userItemList) > 0 {
		thread.AskUserDisplayName = userItemList[0].BasicInfo.DisplayName
		thread.AskUserLogoUri = userItemList[0].BasicInfo.LogoUri
	}

	return &roadmap_qa_api.GetThreadResponse{
		Code:   roadmap_qa_api.GetThreadResponse_CODE_OK,
		Thread: thread,
	}, nil
}

// 只有学生可以删除
func (apiImpl *RoadmapQaApiImpl) RemoveThread(ctx context.Context, req *roadmap_qa_api.RemoveThreadRequest) (*roadmap_qa_api.RemoveThreadResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.RemoveThreadResponse{
			Code:   roadmap_qa_api.RemoveThreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.RemoveThreadResponse{
			Code: roadmap_qa_api.RemoveThreadResponse_CODE_OK,
		}, nil
	}
	if threadItem.AskUserId != sessItem.UserId {
		return &roadmap_qa_api.RemoveThreadResponse{
			Code:   roadmap_qa_api.RemoveThreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = roadmap_dao.ThreadInfoDao.Remove(sessCtx, req.RoadmapId, req.ThreadId)
		if err != nil {
			return nil, err
		}
		//删除内容
		err = roadmap_dao.ThreadContentDao.RemoveByThread(sessCtx, req.ThreadId)
		if err != nil {
			return nil, err
		}
		return &roadmap_qa_api.RemoveThreadResponse{
			Code: roadmap_qa_api.RemoveThreadResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.RemoveThreadResponse), nil
}
